Skip to main content

Python Dictionaries

Dictionaries in Python are mutable, unordered collections that store key-value pairs. Each key in a dictionary must be unique, and the keys are used to access the associated values. Here’s a comprehensive guide to working with dictionaries in Python:

Creating Dictionaries

You can create dictionaries using curly braces {} with key-value pairs separated by colons.

# Creating an empty dictionary

empty_dict = {}

# Creating a dictionary with some key-value pairs

student = {

    "name": "John Doe",

    "age": 20,

    "courses": ["Math", "Computer Science"]

}



Accessing Values

You can access values in a dictionary by using their keys.

# Accessing values by key

print(student["name"])  # Output: John Doe

print(student["age"])   # Output: 20

print(student["courses"])  # Output: ['Math', 'Computer Science']



Modifying Dictionaries

You can modify the values associated with a specific key, add new key-value pairs, and delete existing ones.

Changing Values

# Changing the value associated with a key

 student["age"] = 21

 print(student["age"])  # Output: 21

 



Adding Key-Value Pairs

# Adding a new key-value pair

student["grade"] = "A"

print(student)  # Output: {'name': 'John Doe', 'age': 21, 'courses': ['Math', 'Computer Science'], 'grade': 'A'}


Removing Key-Value Pairs

# Removing a key-value pair using del

del student["grade"]

print(student)  # Output: {'name': 'John Doe', 'age': 21, 'courses': ['Math', 'Computer Science']}

# Removing a key-value pair using pop()

age = student.pop("age")

print(age)      # Output: 21

print(student)  # Output: {'name': 'John Doe', 'courses': ['Math', 'Computer Science']}



Dictionary Methods

Dictionaries come with several built-in methods.

keys(), values(), and items()

These methods are used to access the keys, values, and key-value pairs in the dictionary.

print(student.keys())   # Output: dict_keys(['name', 'courses'])

print(student.values()) # Output: dict_values(['John Doe', ['Math', 'Computer Science']])

print(student.items())  # Output: dict_items([('name', 'John Doe'), ('courses', ['Math', 'Computer Science'])])



update()

This method updates the dictionary with key-value pairs from another dictionary or from an iterable of key-value pairs.

# Updating a dictionary with another dictionary

student.update({"age": 21, "grade": "A"})

print(student)  # Output: {'name': 'John Doe', 'courses': ['Math', 'Computer Science'], 'age': 21, 'grade': 'A'}

# Updating a dictionary with an iterable of key-value pairs

student.update([("age", 22), ("grade", "B")])

print(student)  # Output: {'name': 'John Doe', 'courses': ['Math', 'Computer Science'], 'age': 22, 'grade': 'B'}



get()

This method returns the value for a specified key if the key is in the dictionary, otherwise it returns a default value.

print(student.get("name"))       # Output: John Doe

print(student.get("grade"))      # Output: B

print(student.get("address", "Not Available"))  # Output: Not Available



popitem()

This method removes and returns the last inserted key-value pair as a tuple.

last_item = student.popitem()

print(last_item)  # Output: ('grade', 'B')

print(student)    # Output: {'name': 'John Doe', 'courses': ['Math', 'Computer Science'], 'age': 22}



clear()

This method removes all items from the dictionary.

student.clear()

print(student)  # Output: {}

 

Summary

  • Creating Dictionaries: Use curly braces {} with key-value pairs separated by colons.
  • Accessing Values: Use keys to access values.
  • Modifying Dictionaries: Add, change, and remove key-value pairs.
  • Dictionary Methods: Use methods like keys(), values(), items(), update(), get(), popitem(), and clear().
  • Iterating Over Dictionaries: Iterate over keys, values, and key-value pairs.

Dictionaries are highly versatile and useful for various applications, including data representation, counting, and simple databases. Mastering dictionaries will greatly enhance your ability to work with structured data in Python.

 

 

Comments

Popular posts from this blog

TechUplift: Elevating Your Expertise in Every Click

  Unlock the potential of data with SQL Fundamental: Master querying, managing, and manipulating databases effortlessly. Empower your database mastery with PL/SQL: Unleash the full potential of Oracle databases through advanced programming and optimization. Unlock the Potential of Programming for Innovation and Efficiency.  Transform raw data into actionable insights effortlessly. Empower Your Data Strategy with Power Dataware: Unleash the Potential of Data for Strategic Insights and Decision Making.

Relationships between tables

In Power BI, relationships between tables are essential for creating accurate and insightful reports. These relationships define how data from different tables interact with each other when performing analyses or creating visualizations. Here's a detailed overview of how relationships between tables work in Power BI: Types of Relationships: One-to-one (1:1):   This is the most common type of relationship in Power BI. It signifies that one record in a table can have multiple related records in another table. For example, each customer can have multiple orders. Many-to-One (N:1):   This relationship type is essentially the reverse of a one-to-many relationship. Many records in one table can correspond to one record in another table. For instance, multiple orders belong to one customer. One-to-Many (1:N):   Power BI doesn't support direct one-to-many relationships.  One record in table can correspond to many records in another table.  Many-to-Many (N:N):  ...

SQL Fundamentals

SQL, or Structured Query Language, is the go-to language for managing relational databases. It allows users to interact with databases to retrieve, manipulate, and control data efficiently. SQL provides a standardized way to define database structures, perform data operations, and ensure data integrity. From querying data to managing access and transactions, SQL is a fundamental tool for anyone working with databases. 1. Basics of SQL Introduction : SQL (Structured Query Language) is used for managing and manipulating relational databases. SQL Syntax : Basic structure of SQL statements (e.g., SELECT, INSERT, UPDATE, DELETE). Data Types : Different types of data that can be stored (e.g., INTEGER, VARCHAR, DATE). 2. SQL Commands DDL (Data Definition Language) : CREATE TABLE : Define new tables. ALTER TABLE : Modify existing tables. DROP TABLE : Delete tables. DML (Data Manipulation Language) : INSERT : Add new records. UPDATE : Modify existing records. DELETE : Remove records. DQL (Da...